; Inno Setup 安装脚本文件
; DesktopTimer - 计时助手
; Copyright (c) 2025 Vere. All rights reserved.

; ==================== 应用程序配置 ====================
#define MyAppName "DesktopTimer"
#define MyAppVersion "0.4.1"
#define MyAppPublisher "beipiao_boy"
#define MyAppURL "https://gitee.com/beipiao_boy/DesktopTimer"
#define MyAppExeName "DesktopTimer.exe"
#define MyAppIcon "app\resource\ico\DesktopTimer.ico"
#define MyAppExePath "bin"
#define MyAppInstallPath "C:\\Program Files\\DesktopTimer"
; 应用程序唯一标识 GUID (工具 -> 生成 GUID)
#define MyUid "A5B8C7D6-E4F3-4A2B-1155-7E6F5A4B3C2D"


[Setup]
; ==================== 安装程序基本设置 ====================
; 应用程序唯一标识
AppId={{{#MyUid}}
; 应用程序名称
AppName={#MyAppName}
; 应用程序版本号
AppVersion={#MyAppVersion}
AppVerName={#MyAppName} {#MyAppVersion}
; 发布者信息
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
; 版权信息
AppCopyright=© 2025 Vere. All rights reserved.
; 默认安装目录
DefaultDirName={#MyAppInstallPath}
; 是否使用之前的安装目录
UsePreviousAppDir=yes
; 不显示程序组选择页面
DisableProgramGroupPage=yes
; 以管理员权限运行安装
PrivilegesRequired=admin
; 输出目录和文件名
OutputDir=package
OutputBaseFilename=DesktopTimer_v{#MyAppVersion}_Setup
; 压缩设置
Compression=lzma2/max
SolidCompression=yes
; 现代安装向导风格
WizardStyle=modern
; 图标设置
SetupIconFile={#MyAppIcon}
UninstallDisplayIcon={app}\{#MyAppExeName}
; 许可协议文件（可选）
;LicenseFile=LICENSE.txt
; 安装前/后说明文件（可选）
;InfoBeforeFile=README.txt
;InfoAfterFile=CHANGELOG.txt
; 架构支持
ArchitecturesAllowed=x64
ArchitecturesInstallIn64BitMode=x64

[Languages]
; ==================== 支持的语言 ====================
Name: "chinesesimplified"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
Name: "english"; MessagesFile: "compiler:Default.isl"

[Tasks]
; ==================== 用户可选任务 ====================
; 创建桌面图标
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
; 创建快速启动栏图标
Name: "quicklaunchicon"; Description: "{cm:CreateQuickLaunchIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked; OnlyBelowVersion: 6.1; Check: not IsAdminInstallMode

[Files]
; ==================== 安装文件列表 ====================
; 主程序
Source: "{#MyAppExePath}\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
; 所有文件（包括 Qt DLL、资源等）
Source: "{#MyAppExePath}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; 注意: 对于纯系统文件，使用 "Flags: onlyifdoesntexist"

[Icons]
; ==================== 快捷方式 ====================
; 开始菜单
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
; 桌面图标
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
; 快速启动栏
Name: "{userappdata}\Microsoft\Internet Explorer\Quick Launch\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: quicklaunchicon

[Run]
; ==================== 安装完成后执行 ====================
; 安装完成后运行程序（可选）
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent

[UninstallDelete]
; ==================== 卸载时删除的文件 ====================
; 删除日志文件
Type: filesandordirs; Name: "{app}\logs"
; 删除临时文件
Type: filesandordirs; Name: "{app}\temp"

[Code]

var
  globalInstallPath: String;

// 初始化安装向导
procedure InitializeWizard;
begin
  WizardForm.DirEdit.Text := globalInstallPath;
end;

// 检查程序是否正在运行
function IsAppRunning(const FileName: string): Boolean;
var
  FWMIService: Variant;
  FSWbemLocator: Variant;
  FWbemObjectSet: Variant;
begin
  Result := false;
  try
    FSWbemLocator := CreateOleObject('WBEMScripting.SWBEMLocator');
    FWMIService := FSWbemLocator.ConnectServer('', 'root\CIMV2', '', '');
    FWbemObjectSet := FWMIService.ExecQuery(Format('SELECT Name FROM Win32_Process Where Name="%s"',[FileName]));
    Result := (FWbemObjectSet.Count > 0);
    FWbemObjectSet := Unassigned;
    FWMIService := Unassigned;
    FSWbemLocator := Unassigned;
  except
    Result := false;
  end;
end;

// 获取历史安装路径
function GetInstallString(): String;
var
  InstallPath: String;
begin
  InstallPath := '{#MyAppInstallPath}';
  if RegValueExists(HKLM, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{{#MyUid}}_is1', 'Inno Setup: App Path') then
  begin
    RegQueryStringValue(HKLM, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{{#MyUid}}_is1', 'Inno Setup: App Path', InstallPath)
  end;
  result := InstallPath;
end;

// 准备安装
function InitializeSetup(): Boolean;
var
  ResultStr: String;
  ResultCode: Integer;
begin
  globalInstallPath := GetInstallString();
  result := IsAppRunning('{#MyAppExeName}');
  
  if result then
  begin
    MsgBox('检测到 {#MyAppName} 正在运行，请先关闭程序后再安装！', mbError, MB_OK);
    result := false;
  end
  else if RegQueryStringValue(HKLM, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{{#MyUid}}_is1', 'UninstallString', ResultStr) then
  begin
    if MsgBox('检测到已安装的 {#MyAppName}。' + #13#10 + #13#10 + '是否卸载旧版本后继续安装？' + #13#10 + #13#10 + '注意：这将保留您的历史数据和配置。', mbConfirmation, MB_YESNO) = IDYES then
    begin
      ResultStr := RemoveQuotes(ResultStr);
      Exec(ResultStr, '/SILENT', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
    end;
    result := true;
  end
  else
  begin
    result := true;
  end;
end;

// 准备卸载
function InitializeUninstall(): Boolean;
begin
  result := IsAppRunning('{#MyAppExeName}');
  
  if result then
  begin
    MsgBox('检测到 {#MyAppName} 正在运行，请先关闭程序后再卸载！', mbError, MB_OK);
    result := false;
  end
  else
  begin
    result := true;
  end;
end;

// 卸载前询问是否保留数据
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
  if CurUninstallStep = usUninstall then
  begin
    if MsgBox('是否保留配置文件和日志数据？' + #13#10 + #13#10 + '选择"是"将保留您的所有配置和历史记录。' + #13#10 + '选择"否"将完全删除所有数据。', mbConfirmation, MB_YESNO) = IDNO then
    begin
      // 用户选择不保留，删除所有数据
      DelTree(ExpandConstant('{app}\logs'), True, True, True);
      DelTree(ExpandConstant('{app}\temp'), True, True, True);
      DelTree(ExpandConstant('{app}\bin\temp'), True, True, True);
      // 可以根据需要添加更多需要删除的目录
    end;
  end;
end;
